package etcd

import (
	"context"
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"log"
	"log-agent/conf"
	"time"
)

var (
	DefaultClient *clientv3.Client
)

func Get(key string) ([]byte, error) {
	var err error
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer func() { cancel() }()
	resp, err := DefaultClient.Get(ctx, key)
	if err != nil {

		return nil, err
	}

	// 读配置信息的第一个值
	return resp.Kvs[0].Value, nil
}

func Watch(key string) <-chan []byte {
	respChan := make(chan []byte, 10)
	go func() {
		for resp := range DefaultClient.Watch(context.Background(), key) {
			for _, e := range resp.Events {
				log.Printf("状态变更类型: %s key:%s value:%s\n",
					e.Type, e.Kv.Key, e.Kv.Value)
				respChan <- e.Kv.Value
			}
		}
	}()
	return respChan
}

func init() {
	var err error
	DefaultClient, err = clientv3.New(clientv3.Config{
		Endpoints: []string{
			fmt.Sprintf("%s:%s", conf.Default.Etcd.IP,
				conf.Default.Etcd.Port),
		},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		log.Fatalf("etcd 连接失败, 错误信息: %v\n", err)
	}
}
